<?php
namespace hema\wechat;

use hema\Http;
use think\facade\Cache;

/**
 * 微信小程序接口
 */
class Wxapp
{
	private $config;
    private $error;
	/**
	 * 构造函数
	 */
	public function __construct($config)
	{
		$this->config = $config;
	}
	
	/**
     * 获取不限制数量的小程序码
     * $path = 存放文件夹
     */
    public function getUnlimitedQRCode($path='',string $scene = '',$page = 'pages/index/index')
    {
        $path = 'qrcode/' . $path;
        $file_name = $path . '/' . $scene . '.png';
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $queryarr = [
            'scene' => $scene,
            'page' => $page,
            'check_path' => false,//不检测页面是否存在
            //'is_hyaline' => true,//透明底色
        ];
        $result = Http::post($url,json_encode($queryarr));
        //严正是否返回JSON数据
        if(is_json($result)){
            return $this->result($result);
        }
        if(!file_exists('./'.$path)){
            @mkdir('.'.$path,0777,true);
        } 
        file_put_contents('./'.$file_name,$result); 
        //获取的二维码数据存储到指定的文件
        return $file_name;

    }
	
	/**
     * 小程序登录
    */
    public function code2Session(string $code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $params = [
            'appid' => $this->config['app_id'],
            'secret' => $this->config['app_secret'],
            'grant_type' => 'authorization_code',
            'js_code' => $code
        ];
        return $this->result(Http::get($url, $params));
    }
    
	
    /**
     * 获取令牌 - AccessToken
    */
    private function getAccessToken()
    {
        $config = $this->config;
        if(!$access_token = Cache::get('access_token_' . $config['app_id'])){
            //重新获取
            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            $params = [
                'grant_type' => 'client_credential',
                'appid' => $config['app_id'],
                'secret' => $config['app_secret']
            ];
            $result = json_decode(Http::get($url, $params),true);
            if(isset($result['access_token'])){
                $access_token = $result['access_token'];
                Cache::set('access_token_' . $config['app_id'], $access_token, 7000); //设置将近2小时失效
            }
        }
        return $access_token;
    }
    
    /**
     * 请求数据验证
     **/
    private function result($result)
    {
        $result = json_decode($result,true);
        if(!is_array($result)){
            $this->error = '未知错误';
			return false;
        }
        if(isset($result['errcode']) and $result['errcode']!=0){
			$this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
			return false;
		}
		return $result;
    }
    
    public function getError()
    {
        return $this->error;
    }
}